<template>
  <Container class="mobile-form-modal">
    <div class="mobile-form-modal-inner">
      <div class="title">{{ $t("form.updateEmail.title") }}</div>
      <a-form class="form" :model="formState" ref="formRef">
        <a-form-item
          class="form-item"
          :label="$t('form.updateEmail.form.item_1.label')"
          name="oldemail"
          v-if="memberStore.profile?.email"
          :rules="[{ validator: checkOldEmail, trigger: 'blur' }]"
        >
          <a-input
            :maxlength="30"
            v-model:value.trim="formState.oldemail"
            :placeholder="$t('form.updateEmail.form.item_1.rules.error_1')"
          ></a-input>
        </a-form-item>
        <a-form-item
          class="form-item"
          :label="$t('form.updateEmail.form.item_2.label')"
          name="email"
          :rules="[{ validator: checkNewEmail, trigger: 'blur' }]"
        >
          <a-input
            :maxlength="30"
            v-model:value.trim="formState.email"
            :placeholder="$t('form.updateEmail.form.item_2.rules.error_1')"
          ></a-input>
        </a-form-item>
        <a-form-item
          class="form-item"
          :label="$t('form.code.label')"
          name="captcha"
          :rules="[{ validator: checkCaptcha, trigger: 'blur' }]"
        >
          <div class="get-code-item">
            <a-input
              :maxlength="6"
              v-model:value.trim="formState.captcha"
              :placeholder="$t('form.code.placeholder')"
            ></a-input>
            <a-button class="getCode" @click="getCode" v-if="!tempCode">{{
              $t("form.code.get_code")
            }}</a-button>
            <tepmlate v-else>
              <a-button class="getCode" @click="getCode" v-if="!getCoding">{{
                $t("form.code.re_get_code")
              }}</a-button>
              <a-button class="getCode getCoding" v-else
                >{{ codeNumber }}s</a-button
              >
            </tepmlate>
          </div>
        </a-form-item>
      </a-form>
      <div class="footer-btn">
        <div class="footer-btn-inner">
          <a-button @click="goBack">{{ $t("btnText.cancel") }}</a-button>
          <a-button
            class="ensure-btn"
            :class="formIsValid ? '' : 'disabled'"
            type="primary"
            @click="continuePublish"
            >{{ $t("btnText.ensure") }}</a-button
          >
        </div>
      </div>
    </div>
  </Container>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, onMounted, ref } from "vue";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";
import { useMemberStore } from "../../store";
import type { UpdateEmailParams } from "../../types/member";
import { RegEmail } from "../../data/reg";
import { postSendEmailCode } from "../../api/api";
import { postUpdateEmail } from "../../api/member";

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

const router = useRouter();
const memberStore = useMemberStore();

const initForm = () => {};

const formIsValid = computed(() => {
  let flag = true;
  if (!formState.value.oldemail) flag = false;
  if (!formState.value.email) flag = false;
  if (!formState.value.captcha) flag = false;
  return flag;
});

// Form Rules
const checkOldEmail = (_Rule: any, value: string) => {
  if (!memberStore.profile!.email) return Promise.resolve();
  if (!value) {
    return Promise.reject($t("form.updateEmail.form.item_1.rules.error_1"));
  }
  if (!RegEmail.test(value)) {
    return Promise.reject($t("reg_rules.email"));
  }
  if (value !== memberStore.profile!.email) {
    return Promise.reject($t("form.updateEmail.no_match"));
  } else {
    return Promise.resolve();
  }
};

const checkCaptcha = (_Rule: any, value: string) => {
  if (!tempCode.value) {
    return Promise.reject($t("form.code.error_1"));
  }
  if (value != tempCode.value) {
    return Promise.reject($t("form.code.error_2"));
  }
  return Promise.resolve();
};
const emailIsValid = ref(false);
const checkNewEmail = (_Rule: any, value: string) => {
  if (!value) {
    emailIsValid.value = false;
    return Promise.reject($t("form.updateEmail.form.item_2.rules.error_1"));
  }
  if (!RegEmail.test(value)) {
    emailIsValid.value = false;
    return Promise.reject($t("reg_rules.email"));
  } else {
    emailIsValid.value = true;
    return Promise.resolve();
  }
};

const tempCode = ref("");
let getCoding = ref(false);
let getCodeTimer: any = null;
let codeNumber = ref(60);
const getCode = async () => {
  if (!emailIsValid.value) return message.error($t("reg_rules.email"));
  if (getCodeTimer) return;
  let res = await postSendEmailCode({
    email: formState.value.email,
    type: "update_email",
  });
  if (res.code === 200) {
    message.success($t("message.changed_success"));
    getCoding.value = true;
    tempCode.value = res.captcha!;
    getCodeTimer = setInterval(() => {
      if (codeNumber.value === 0) {
        clearInterval(getCodeTimer);
        getCoding.value = false;
        codeNumber.value = 60;
        getCodeTimer = null;
      }
      codeNumber.value--;
    }, 1000);
  } else {
    message.error($t("message.error.update"));
  }
};

// 发布
const formState = ref<UpdateEmailParams & { oldemail?: string }>({
  oldemail: "",
  email: "",
  captcha: "",
});

const formRef = ref();

const continuePublish = () => {
  if (!formIsValid.value) return;
  formRef.value.validate().then(async () => {
    let res = await postUpdateEmail(formState.value);
    if (res.code === 200) {
      message.success($t("message.password_changed"));
      memberStore.profile!.email = formState.value.email;
      goBack();
    } else {
      goBack();
      message.error(res.msg);
    }
  });
};
const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  initForm();
});
</script>
<style lang="less">
.mobile-form-modal {
  .wrap-container > .wrap-pl {
    padding-bottom: 0 !important;
  }
}
</style>
<style scoped lang="less">
@import url("./common.less");
.get-code-item {
  display: flex;
  align-items: center;
  .ant-btn {
    width: 450px !important;
    height: 205px !important;
    border-radius: 61px 61px 61px 61px !important;
    font-size: 62px !important;
    padding: 32px 108px !important;
  }
}
:deep(.form) {
  .ant-form-item {
    .ant-row {
      width: 100%;
      justify-content: space-between;
      flex-wrap: nowrap;
      .ant-col {
        display: flex;
        flex: 0 0 auto;
        padding-bottom: 0;
        &:last-child {
          div:last-child {
            width: 100%;
            text-align: right;
          }
        }
      }
    }
    &:last-child {
      .ant-form-item-label {
        position: relative;
        top: 20px;
      }
    }
  }
}
</style>
